<script setup lang="ts">
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { GroupApi } from '#/api/system/group';

const emit = defineEmits<{ create: [Partial<GroupApi.GroupResult>]; update: [{ data: Partial<GroupApi.GroupResult>; id: string }] }>();
const pk = ref<string>('');
const title = ref<string>('编辑用户组');
const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入名称',
      },
      fieldName: 'name',
      label: '名称',
      rules: 'required',
    },
  ],
  showDefaultActions: false,
  wrapperClass: 'grid-cols-1',
  handleSubmit: async (values: Record<string, any>) => {
    pk.value ? emit('update', { id: pk.value, data: values }) : emit('create', values);
  },
});

const [Modal, modalApi] = useVbenModal({
  onOpenChange(isOpen: boolean) {
    const row = modalApi.getData();
    if (isOpen && row) {
      pk.value = row.id;
      title.value = row.id ? '编辑用户组' : '新增用户组';
      formApi.setValues(row);
    }
  },
  async onConfirm() {
    await formApi.validateAndSubmitForm();
    // await formApi.submitForm();
  },
});
</script>

<template>
  <Modal :title="title"> <Form /> </Modal>
</template>
